import {useEffect, useState} from 'react';

export const useFetchData = <T = unknown>(fetchData: () =>Promise<T>) => {
    const [isLoading, setLoading] = useState(false)

    const [data, setData] = useState<T | null>(null)

    useEffect(() => {
        const cb = async () => {
            try {
                setLoading(true)
                const response = await fetchData()
                setData(response as T)
            } catch (error) {
                setData(null)
                console.error(error)
            } finally {
                setLoading(false)
            }
        }

        void cb()
    },[fetchData])

    return {
        isLoading,
        data,
    }
}
